<template>
  <div>
    <!-- 固定操作栏 -->
    <FixedOperation>
      <div class="flex items-center justify-between">
        <div class="leading-30px">
          <div class="inline-block">
            <svg-icon
              :icon-class="'svg_yjfk'"
              class="w-30px h-30px align-middle"
            />
            <span
              class="text-#000 leading-30px ml-10px text-16px font-bold align-bottom"
              >意见反馈</span
            >
          </div>
        </div>
        <!-- 内容 -->
        <div class="text-right">
          <slot></slot>
          <el-button
            v-if="!formModel.id"
            type="primary"
            plain
            @click="handleSaveFn"
          >
            提交建议
          </el-button>
          <el-button
            type="primary"
            plain
            @click="handleSaveFn"
            v-else-if="!isReply && formModel.id && authority"
            >回复</el-button
          >
          <el-button type="primary" plain @click="handleBack">返回</el-button>
        </div>
      </div>
    </FixedOperation>
    <div class="py-20px m-auto w-70%">
      <el-form
        ref="formRef"
        :model="formModel"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="反馈类型：" prop="type">
              <el-radio-group v-model="formModel.type">
                <template v-for="(item, index) in feedback_type" :key="index">
                  <el-radio-button
                    :disabled="formModel.id ? true : false"
                    :label="item.value"
                    :value="item.value"
                    >{{ item.label }}</el-radio-button
                  >
                </template>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="标题：" prop="title">
              <el-input
                v-model="formModel.title"
                maxlength="50"
                :disabled="formModel.id ? true : false"
                placeholder="请输入标题"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="模块名称：" prop="moduleName">
              <el-input
                v-model="formModel.moduleName"
                placeholder="请输入相关模块或功能名称"
                :disabled="formModel.id ? true : false"
                maxlength="90"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详情描述：" prop="detail">
              <div v-if="formModel.id" class="w-100% editorHtmlSty">
                <div v-html="formModel.detail"></div>
              </div>
              <editor
                v-else
                v-model="formModel.detail"
                :min-height="192"
                @myClick="changeText"
                :isToolbar="formModel.id ? false : true"
                :readOnly="formModel.id ? true : false"
                class="w-100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="上传附件：">
              <el-upload
                v-model:file-list="formModel.fileList"
                class="upload-demo"
                action="#"
                :disabled="formModel.id ? true : false"
                :before-upload="beforeAvatarUpload"
                :http-request="handleFileChange"
                accept=".rar, .zip, .doc, .docx, .pdf"
                :show-file-list="false"
              >
                <el-button
                  type="default"
                  style="font-size: 14px"
                  :disabled="formModel.id ? true : false"
                  ><el-icon><UploadFilled /></el-icon>上传文件</el-button
                >
                <template #tip>
                  <div class="el-upload__tip float-right">
                    支持格式：.rar .zip .doc .docx .pdf ，单个文件不能超过100MB
                  </div>
                </template>
              </el-upload>
              <div class="text-14px mt-10px" style="width: 100%">
                <div v-for="(item, index) in fileList" :key="item.fileId">
                  <a :href="item.url" target="_blank" class="text-#409eff">{{
                    item.origFileName
                  }}</a>
                  <el-button
                    text
                    plain
                    @click="delFileName(index)"
                    :disabled="formModel.id ? true : false"
                    >删除</el-button
                  >
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="联系方式：" prop="tel">
              <el-input
                v-model="formModel.tel"
                maxlength="40"
                :disabled="formModel.id ? true : false"
                placeholder="请输入手机号码/QQ/邮箱"
              />
            </el-form-item>
          </el-col>
          <el-col
            :span="24"
            v-if="(formModel.id && authority) || formModel.status == 1"
          >
            <el-form-item label="回复：" prop="replyContent">
              <el-input
                type="textarea"
                v-model="formModel.replyContent"
                maxlength="950"
                :rows="7"
                :disabled="isReply"
                placeholder="请输入回复内容"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>
<script setup name="Feedbacks">
import useTagsViewStore from '@/store/modules/tagsView'
import { skipToError } from '@/utils/commo'
import { uploadFile, delFile } from '@/api/salesManage/contractManage'
import * as API from '@/api/system/opinion'
import useUserStore from '@/store/modules/user'
import { reactive, toRefs } from 'vue'
const { proxy } = getCurrentInstance()
const { feedback_type } = proxy.useDict('feedback_type')
// 通用数据store
const router = useRouter()
const data = reactive({
  formModel: {
    id: null,
    replyContent: null,
    type: '1'
  },
  rules: {
    type: [
      {
        required: true,
        message: '反馈类型不能为空',
        trigger: ['blur', 'change']
      }
    ],
    title: [
      {
        required: true,
        message: '标题不能为空',
        trigger: ['blur', 'change']
      }
    ],
    moduleName: [
      {
        required: true,
        message: '模块名称不能为空',
        trigger: ['blur', 'change']
      }
    ],
    detail: [
      {
        required: true,
        message: '详情描述不能为空',
        trigger: ['blur', 'change']
      }
    ],
    replyContent: [
      {
        required: true,
        message: '回复不能为空',
        trigger: ['blur', 'change']
      }
    ]
  }
})
const { formModel, rules } = toRefs(data)
console.log(useUserStore(), ' useUserStore()')
const authority = ref(false) // 是否具有权限

function getAuth() {
  // 是否为意见管理员
  const hasAuth =
    useUserStore().roles.includes('opinion') ||
    useUserStore().roles.includes('admin')
  authority.value = !!hasAuth
}
getAuth()
console.log(authority.value, 'authority')
const isReply = ref(false) //是否回复完成
/** 清除编辑器的表单验证 */
const changeText = text => {
  if ((text && text == '<p></p>') || text == '<p><br></p>') {
    formModel.value.detail = null
    proxy.$refs['formRef'].validateField('detail')
    return false
  }
  if (formModel.value.detail) {
    proxy.$refs['formRef'].clearValidate('detail') // clearValidate()取消验证方法
  }
}
// 查询详情数据
async function init() {
  const res = await API.detailsSysAdvice({ id: formModel.value.id })
  formModel.value = res.data
  isReply.value = res.data?.replyContent ? true : false
  fileList.value = res.data ? res.data.sysAttachFiles : []
}
// 提交建议
const handleSaveFn = () => {
  proxy.$refs['formRef'].validate(async valid => {
    if (!valid) {
      skipToError()
      return false
    }
    let params = JSON.parse(JSON.stringify(formModel.value))
    params.sysAttachFiles = fileList.value
    delete params.fileList
    if (formModel.value.id) {
      //回复
      API.editSysAdvice(params).then(res => {
        proxy.$modal.msgSuccess('操作成功')
        handleBack()
      })
    } else {
      delete params.id
      //新增 意见反馈
      API.addSysAdvice(params).then(res => {
        proxy.$modal.msgSuccess('操作成功')
        handleBack()
      })
    }
  })
}
// 返回
const handleBack = () => {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
}
/*** 文件上传 start */
let fileList = ref([])
/**文件上传 限制条件
 *
 * @param {*} rawFile
 */
function beforeAvatarUpload(rawFile) {
  if (rawFile.size / 1024 / 1024 > 100) {
    proxy.$modal.msgError('单个文件不能超过100MB!')
    return false
  }
}
// 上传合同
async function handleFileChange(params) {
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      fileList.value.push(res.data)
    }
  } catch (error) {
    console.log(error)
    proxy.$modal.msgError(error)
  }
}
// 删除文件
async function delFileName(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      //招标
      const file = fileList.value[index]

      const res = await delFile(file.fileName)
      if (res.code === 200) {
        fileList.value.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}
/*****文件上传 end */
const route = useRoute()
watch(
  () => route.query.id,
  val => {
    if (route.query.id && location.href.match(/feedbacks/)) {
      formModel.value.id = route.query.id
      init()
    }
  },
  {
    immediate: true
  }
)
</script>
<style lang="scss">
.editorHtmlSty {
  div {
    height: 400px;
    overflow-y: auto;
    border: 1px solid #d1d5db;
    padding: 0 12px;
    scrollbar-width: none; //兼容火狐
    -ms-overflow-style: none; //兼容IE10+
    &::-webkit-scrollbar {
      display: none; // 使用伪类选择器 ::-webkit-scrollbar ,兼容chrome和safari浏览器
    }
    p {
      @apply m-0 p-0;
      img {
        @apply w-100%;
      }
    }
  }
}
</style>
